<template>
  <div v-loading="loading" element-loading-text="系统处理中">
    <div class="bread-box but20">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item class="btn-green" style=" color: #3DC094;" @click.native="goBack">门店建设整体跟进</el-breadcrumb-item>
        <el-breadcrumb-item>市场交接</el-breadcrumb-item>
      </el-breadcrumb>
      <div>
        <el-button type="primary" size="mini" @click.native="submitForm('save')">保存</el-button>
        <el-button size="mini" @click.native="goBack">返回</el-button>
      </div>
    </div>
    <div class="mt20">
      <!-- <div class="qup-title-box">
        <span class="border" /><span>门店建设市场交接申请</span>
      </div> -->
      <el-form ref="refForm" :model="formData" :rules="formRules" size="mini" label-width="120px">
        <el-row class="form_item_height">

          <el-col :xs="12" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="门店建设项目号:" prop="constCode">{{ queryObj.constCode }}</el-form-item>
          </el-col>
          <el-col :xs="12" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="门店建设当前进度:" prop="modifName">{{ formaterData(beforeConstSchedule, queryObj.constSchedule) }}</el-form-item>
          </el-col>

        </el-row>
        <!-- =====================交接前数据 -->
        <div class="qup-title-box">
          <span class="border" /><span>交接前数据</span>
        </div>
        <el-row class="form_item_height">

          <el-col :span="8">
            <el-form-item label="交接前门店编码:" prop="beforeShopCode">
              <span>{{ formData.beforeShopCode }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="交接前门店名称:" prop="beforeShopName">
              <span>{{ beforeShopName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="所属客户编码:" prop="beforeCustomerCode">
              <span>{{ beforeCustomerCode }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="所属客户名称:" prop="beforeCustomerName">
              <span>{{ beforeCustomerName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="所属办事处:" prop="beforeOfficeName">
              <span>{{ beforeOfficeName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="门店类型:" prop="beforeShopClassify">
              <span>{{ beforeShopClassify }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="门店业务类型:" prop="beforeBusinessType">
              <span>{{ beforeBusinessType }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="门店城市级别:" prop="beforeCityLevel">
              <span>{{ beforeCityLevel }}</span>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="门店详细地址:" prop="beforeShopAddr">
              <span>{{ beforeShopAddr }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- ======================交接后数据 -->
        <div class="qup-title-box">
          <span class="border" /><span>交接后数据</span>
        </div>
        <el-row class="form_item_height">
          <el-col :span="8">
            <el-form-item label="交接后门店:" prop="newShop">
              <input-with-dialog
                v-model="formData.newShop"
                :props="{label:'name',value:'code'}"
                :multiple="false"
                :focus-query="true"
                :config="shopDialogConfig"
                @change="handleChangeNewShop"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="门店编码:" prop="afterShopCode">
              <span>{{ formData.afterShopCode }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="所属客户编码:" prop="afterCustomerCode">
              <span>{{ afterCustomerCode }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="所属客户名称:" prop="afterCustomerName">
              <span>{{ afterCustomerName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="所属办事处:" prop="officeName">
              <span>{{ afterOfficeName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="门店类型:" prop="shopType">
              <span>{{ afterShopClassify }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="门店业务类型:" prop="shopBizType">
              <span>{{ afterBusinessType }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="门店城市级别:" prop="shopCityLevel">
              <span>{{ afterCityLevel }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="门店详细地址:" prop="shopAddress">
              <span>{{ afterShopAddr }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="交接日期:" prop="shopChangeTime">
              <el-date-picker
                v-model="formData.shopChangeTime"
                value-format="yyyy-MM-dd HH:mm:ss"
                align="right"
                type="datetime"
                placeholder="选择日期"
                :picker-options="pickerOptions"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item v-show="typeFlag==='dataTransition'" label="客户经理:" size="mini" prop="customerManagerAccount" :rules="[{ required: typeFlag==='dataTransition', message: '请选择客户经理' }]">
              <input-with-dialog
                v-model="manager"
                :props="{label:'userName',value:'account'}"
                :multiple="false"
                :config="managerConfig"
                @change="managerChange"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="交接说明:" prop="exceptionDesc">
              <el-input v-model="formData.exceptionDesc" placeholder="请输入交接说明" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="申请人:" prop="createBy">
              <span>{{ formData.createBy }}</span>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="8">
            <el-form-item label="申请时间:" prop="modifName">
              2014-06-16
            </el-form-item>
          </el-col> -->
        </el-row>
      </el-form>
    </div>

  </div>
</template>

<script>
// import imgUpload from '../../components/ImgUploader/ImgUploader'  图片上传组件
import { getUserInfo } from '@/utils/auth'
import { getDictByPatchType } from '@/api/dataDict'
import { submitMarketApply, getExceptionType } from '@/api/storeConstruction'
export default {
  name: 'MarketApply',
  // components: {
  //   imgUpload
  // },
  props: {
    detailData: {
      type: [String, Object],
      default: ''
    },
    typeFlag: {
      type: String,
      default: ''
    }
  },

  data() {
    return {
      loading: false,
      manager: [],
      formData: {},
      queryObj: {
        shopExceptionDetailDTOS: []
      },
      shop: [],
      newShop: [],
      beforeShopName: '',
      beforeCustomerName: '',
      beforeCustomerCode: '',
      beforeOfficeName: '',
      beforeShopClassify: '',
      beforeBusinessType: '',
      beforeCityLevel: '',
      beforeShopAddr: '',
      afterCustomerName: '',
      afterCustomerCode: '',
      afterOfficeName: '',
      afterShopClassify: '',
      afterBusinessType: '',
      afterCityLevel: '',
      afterShopAddr: '',
      exceptionHandle: {},
      beforeConstSchedule: [],
      cityTypeList: [],
      shopBizTypeList: [],
      shopTypeList: [],
      // 门店
      shopDialogConfig: {
        title: '门店',
        interfacePath: `/select-service/api/v1/shop/page`,
        setting: [
          {
            prop: 'code',
            title: '门店编码'
          },
          {
            prop: 'name',
            title: '门店名称'
          }
        ]
      },
      managerConfig: {
        title: '客户经理',
        filtersRaw: [{ id: 'passwordValidWay', property: 'passwordValidWay', operator: '=', value: 2 }],
        interfacePath: `${process.env.VUE_APP_BASE_API}/api/v1/user/domainMarketingUser/page`,
        setting: [
          {
            prop: 'account',
            title: '编码'
          },
          {
            prop: 'userName',
            title: '名称'
          },
          {
            prop: 'orgCode',
            title: '所属组织编码'
          },
          {
            prop: 'orgName',
            title: '所属组织名称'
          }
        ]
      },
      formRules: {
        newShop: [
          { required: true, message: '请选择交接后门店' }
        ],
        shopChangeTime: [
          { required: true, message: '请选择交接日期' }
        ],
        exceptionDesc: [
          { required: true, message: '请输入交接说明' }
        ]
      },
      pickerOptions: {
        disabledDate(time) {
          var date = new Date()
          var y = date.getFullYear()
          var m = date.getMonth() + 1
          var d = date.getDate()
          var nowTime = new Date(`${y}-${m}-${d} 00:00:00`)
          return time.getTime() < nowTime.getTime()
        }
      },
      items: [],
      btnList: [], // 按钮权限
      les: `https://uacdev.quanyou.com.cn/price-center/api/v1/priceWholesaleStandard/search`,
      interfacePath: `https://uacdev.quanyou.com.cn/price-center/api/v1/defPriceType/page` // 调公共接口
    }
  },
  computed: {
    nowvisible: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    }
  },

  async created() {
    this.queryObj = JSON.parse(JSON.stringify(this.detailData))
    const { userName } = getUserInfo()
    this.formData.createBy = userName
    await this.getDictByPatchTypeAll(['BEFORE_CONST_SCHEDULE', 'CITY_LEVEL', 'BIZ_TYPE', 'SHOP_TYPE'])
      .then(res => {
        this.beforeConstSchedule = res.BEFORE_CONST_SCHEDULE // 门店建设整体进度
        this.cityTypeList = res.CITY_LEVEL // 门店建设类型
        this.shopBizTypeList = res.BIZ_TYPE // 业务类型
        this.shopTypeList = res.SHOP_TYPE // 门店类型
      })
    this.formData.beforeShopCode = this.detailData.shopCode
    this.beforeShopName = this.detailData.shopName
    this.beforeCustomerName = this.detailData.customerName
    this.beforeCustomerCode = this.detailData.customerCode
    this.beforeOfficeName = this.detailData.officeName
    this.beforeShopClassify = this.formaterData(this.shopTypeList, this.detailData.shopType)
    this.beforeBusinessType = this.formaterArr(this.shopBizTypeList, this.detailData.shopBizType)
    this.beforeCityLevel = this.formaterData(this.cityTypeList, this.detailData.shopCityLevel)
    this.beforeShopAddr = this.detailData.shopAddress
    const obj = [{ 'id': 'exceptionType', 'property': 'exceptionType', 'operator': '=', 'value': '市场交接' }]
    const shopFilter = [{ 'id': 'code', 'property': 'code', 'operator': '<>', 'value': this.formData.beforeShopCode },
      { 'id': 'agencyCode', 'property': 'agencyCode', 'operator': '=', 'value': this.detailData.officeCode },
      { 'id': 'status', 'property': 'status', 'operator': '=', 'value': 1 }]
    this.$set(this.shopDialogConfig, 'filtersRaw', shopFilter)
    const formData = new FormData()
    formData.append('filtersRaw', JSON.stringify(obj))
    await getExceptionType(formData).then(res => {
      if (res.success && res.data && res.data.records) {
        this.exceptionHandle = res.data.records[0]
        this.queryObj.exceptionHandleId = this.exceptionHandle.id
        this.queryObj.modelId = this.queryObj.id
      }
    })
  },
  methods: {
    // 选择客户经理
    managerChange(data) {
      if (data && data.length) {
        this.$set(this.formData, 'customerManagerAccount', data[0].account)
        this.$set(this.formData, 'customerManagerName', data[0].userName)
      } else {
        this.$set(this.formData, 'customerManagerAccount', '')
        this.$set(this.formData, 'customerManagerName', '')
      }
    },
    // 获取数据字典
    async getDictByPatchTypeAll(data) {
      const obj = await getDictByPatchType(data)
        .then(res => {
          return res
        })
      return obj
    },
    // 格式化数据
    formaterData(arr, dictCode) {
      // if (!arr || !dictCode) return
      const tmpArr = arr.filter(item => item.dictCode === dictCode)
      if (tmpArr.length) {
        return tmpArr[0].dictName
      }
      return dictCode
    },
    formaterArr(dataList, str) {
      if (!str || !str.length) return
      let list = []
      if (typeof (str) === 'string') {
        list = str.split(',')
      } else {
        list = str
      }
      const arr = []
      dataList.forEach((item) => {
        const flag = list.some(v => v === item.dictCode)
        if (flag) {
          arr.push(item.dictName)
        }
      })
      return arr.toString()
    },
    // 交接前门店
    handleChangeNewShop(data) {
      if (data && data.length) {
        const obj = data[0]
        if (obj.code === this.formData.beforeShopCode) {
          this.$message.warning('不可选择交接前门店，请重新选择门店')
          return
        }
        this.formData.afterShopCode = obj.code
        this.afterCustomerName = obj.customerName
        this.afterCustomerCode = obj.customerCode
        this.afterOfficeName = obj.agencyName
        this.afterShopClassify = this.formaterData(this.shopTypeList, obj.shopClassify)
        this.afterBusinessType = obj.businessTypeName
        this.afterCityLevel = this.formaterData(this.cityTypeList, obj.cityLevel)
        this.afterShopAddr = obj.shopAddr
      }
    },
    goBack() {
      this.$confirm('此操作不可逆，是否确认并返回列表界面?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.nowvisible = false
        this.pageShow = false
        // this.$refs.refForm.clearValidate()
        this.$emit('goBack', this.pageShow)
      })
    },
    // 提交表单处理
    submitForm() {
      this.$refs['refForm'].validate((valid) => {
        if (valid) {
          // this.formData.bizCode = this.queryObj.constCode
          // return
          this.loading = true
          const shopExceptionDetailDTOS = []
          shopExceptionDetailDTOS.push(this.formData)
          this.queryObj.shopExceptionDetailDTOS = shopExceptionDetailDTOS
          this.queryObj.bizCode = this.queryObj.constCode
          this.queryObj.exceptionDesc = this.formData.exceptionDesc
          this.$set(this.queryObj, 'customerManagerAccount', this.formData.customerManagerAccount)
          this.$set(this.queryObj, 'customerManagerName', this.formData.customerManagerName)
          this.$set(this.queryObj, 'customerManagerCode', this.formData.customerManagerAccount)

          // this.queryObj.modelId = this.queryObj.id
          // return
          submitMarketApply(this.queryObj).then(res => {
            if (res.success) {
              this.$message.success('操作成功')
              this.formData = {}
              this.$refs.refForm.clearValidate()
              this.$emit('goBack')
            }
            this.loading = false
          }).cattch(() => {
            this.loading = false
          })
        }
      })
    }
  }
}
</script>
<style lang='scss' scoped>
  /deep/ .el-breadcrumb__inner{
    color: $qup-color-primary;
  }
.img-upload-container {
  width: fit-content;
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-end;
  align-items: center;
  .icon-msg{
    margin-left: 10px;
    color: #999;
  }
}
.subdaoch{margin: 10px 0;}
.but20{ margin-bottom: 20px;}
.el-breadcrumb__inner,.btn-green{
    color: #3DC094;
}
.qup-title-box{background: #f2f2f2; line-height: 30px;}

</style>
